﻿package net.wangit.dev.component;

import net.wangit.MapList;
import net.wangit.Row;
import net.wangit.context.ActionContext;
import net.wangit.dev.LabelRule;
import net.wangit.dev.ReferenceUtil;
import net.wangit.jdbc.DB;
import net.wangit.util.Checker;
import net.wangit.view.tree.Tree;

public class DataPrivilegeTree extends ObjectTree {

	private static final String PREFIX = "_06C";
	private static final String TYPE = Integer.toString(6);
	private static final String SQL = "select dpid,dpn,l,gid from DPCONFIG order by o,dpid";
	private static final String COUNT_NAME = "rowcount";
	private static final String ITEM_SQL = "select count(*) rowcount from DP where dpid=?";

	public DataPrivilegeTree() {
	}

	protected String getItemsTableName() {
		return "DP";
	}

	protected String getComponentType() {
		return TYPE;
	}

	protected MapList getObjects(DB db) throws Exception {
		MapList objects = db.query(DataPrivilegeTree.SQL);
		objectCount = Checker.isEmpty(objects) ? 0 : objects.size();
		return objects;
	}

	protected boolean showNullGroup() {
		return true;
	}

	protected String getGroupAttribute() {
		return "oncontextmenu=wmg6()";
	}

	protected int addObject(ActionContext ac, DB db, Tree parent, Row row)
			throws Exception {
		int itemCount = 0;
		Tree object = new Tree();
		String id = row.get("dpid");
		object.setId((new StringBuilder(DataPrivilegeTree.PREFIX)).append(id)
				.toString());
		String name = row.get("dpn");
		String status = row.get("l", "0");
		object.setIcon((new StringBuilder("/domain/dev/c/dp")).append(status)
				.append(".png").toString());
		if (check) {
			name = (new StringBuilder(String.valueOf(id))).append(" ").append(
					name).toString();
		} else {
			MapList referenceData = ReferenceUtil.getDataPrivilegeReference(db,
					id);
			int referenceCount = Checker.isEmpty(referenceData) ? 0
					: referenceData.size();
			itemCount = getItemCount(db, id);
			String label = LabelRule.getLabel(ac, ObjectTreeHelper
					.getLableRule(ac), id, name);
			name = (new StringBuilder(String.valueOf(referenceCount))).append(
					" ").append(label).append(" ").append(itemCount).toString();
			object.setAttribute("oncontextmenu=wm6()");
			object.setAction((new StringBuilder("/dev/dp.do?m=e&dpid="))
					.append(id).toString());
		}
		object.setName(name);
		parent.add(object);
		return itemCount;
	}

	public static int getItemCount(DB db, String id) throws Exception {
		MapList list = db.query(DataPrivilegeTree.ITEM_SQL, id, 2);
		return list.getRow(0).getInt(DataPrivilegeTree.COUNT_NAME, 0);
	}

}
